<template>
  <div class="about">
    <h1>{{id ? '编辑' : '新建' }}物品</h1>

    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="名称">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <!-- :action 动态绑定上传地址 -->
      <el-form-item label="图标">
        <el-upload
          class="avatar-uploader"
          :action="$http.defaults.baseURL + '/upload'"
          :show-file-list="false"
          :on-success="afterUpload"
        >
          <img v-if="model.icon" :src="model.icon" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
        <!-- 点击保存执行的 form submit 事件 -->
      </el-form-item>
    </el-form>
  </div>
</template>


<script>
export default {
  props: {
    id: {}
  },

  data() {
    return {
      model: {}
    };
  },
  methods: {
    async save() {
      console.log("保存 save");
      // 请求接口提交数据 用到axios

      let res;
      if (this.id) {
        // 有id 为编辑模式 根据id 更新 编辑内容
        res = await this.$http.put(`rest/items/${this.id}`, this.model);
      } else {
        // 新增分类
        res = await this.$http.post("rest/items", this.model);
      }

      console.log("res", res);
      this.$router.push("/items/list");
      this.$message({
        type: "success",
        message: "保存成功"
      });
    },

    async fetch() {
      console.log("Edit fetch");

      const res = await this.$http.get(`rest/items/${this.id}`);
      console.log(res);
      this.model = res.data;
    },

    afterUpload(res, file) {
      console.log(file)

      // this.model.icon = res.url;
      // 当model 中没有icon 属性, 后面加一个icon属性 直接赋值 页面无法渲染出来 使用下面的方法 赋值
      this.$set(this.model, 'icon', res.url)
    }
  },
  created() {
    this.id && this.fetch();
  }
};
</script>


<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>